#!/bin/bash

# 备份策略：
# 过去一天内的每小时备份（没必要）
# 过去一月(30天)内的每日备份
# 过去一年(365天)内的每月备份
# 过去一年以上的每年备份
# 
# 文件名：note_yyyy-mm-dd_hh
# 文件夹 year/month/day/hour
# 
# 1.每天备份，加密压缩
# 2.保存到day文件夹，ddhh为0100的备份保存到month，mmddhh为010100的备份保存到year
# 3.删除day文件夹中一月前的备份，month中一年前的备份
# 4.上传每月备份到坚果云
#
# crontab:
# Backup leanote ervey day
# 0 0 * * * /server/script/leanote_backup.sh

function uploadFile()
{
    if [ ! -f $YUN_DIR/index ]; then
        # 坚果云未挂载
        echo "Yun is not mounted, mount it."
        # mount.davfs -t davfs $YUN_URL $YUN_DIR
        umount $YUN_DIR
        mount $YUN_DIR
    fi

    if [ ! -f $YUN_DIR/index ]; then
        # 挂载失败
        echo "Mount yun failed"
        exit 1
    fi

    cp -a $FULL_BAK_FILE_TAR $YUN_BAK_DIR

    echo "upload completed!"
}

LEANOTE_ROOT=/server/leanote
BAK_DIR=/download/local_backup/leanote
BAK_FILE=note_`date "+%Y-%m-%d_%H"`
FULL_BAK_FILE=$BACK_DIR/$BAK_FILE
FULL_BAK_FILE_TAR=$FULL_BAK_FILE.tar.gz
DIR_YEAR=$BAK_DIR/year
DIR_MONTH=$BAK_DIR/month
DIR_DAY=$BAK_DIR/day
DIR_HOUR=$BAK_DIR/hour

YUN_DIR=/download/jianguoyun
YUN_URL=https://dav.jianguoyun.com/dav/backup
YUN_BAK_DIR=$YUN_DIR/leanote

MATCH_YEAR=note_[0-9][0-9][0-9][0-9]-01-01_00
MATCH_MONTH=note_[0-9][0-9][0-9][0-9]-[0-1][0-9]-01_00
MATCH_DAY=note_[0-9][0-9][0-9][0-9]-[0-1][0-9]-[0-2][0-9]_00

if [ ! -d $DIR_YEAR ]; then
    mkdir -p $DIR_YEAR $DIR_MONTH $DIR_DAY $DIR_HOUR
fi

# mongodump -h localhost -d leanote --port 27017 -o $FULL_BAK_FILE
mongodump -u changetoyouruser -p changetoyourpasswd -h localhost -d leanote --port 27017 -o $FULL_BAK_FILE
cp -a $LEANOTE_ROOT/files $FULL_BAK_FILE
# 压缩: tar zcvf - file | openssl des3 -salt -k password -out file.des3.tar.gz
# 解压: openssl des3 -d -k password -salt -in file.des3.tar.gz | tar zxvf -
tar zcvf - $FULL_BAK_FILE | openssl des3 -salt -k sfdsf8fwrj2 -out $FULL_BAK_FILE_TAR
rm -rf $FULL_BAK_FILE

if [[ $BAK_FILE == $MATCH_YEAR ]]; then
    cp $FULL_BAK_FILE_TAR $DIR_YEAR
fi

if [[ $BAK_FILE == $MATCH_MONTH ]]; then
    cp $FULL_BAK_FILE_TAR $DIR_MONTH
    find $DIR_MONTH -mtime +365 -delete
fi

# if [[ $BAK_FILE == $MATCH_DAY ]]; then
    cp $FULL_BAK_FILE_TAR $DIR_DAY
    find $DIR_DAY -mtime +30 -delete
# fi

# cp $FULL_BAK_FILE_TAR $DIR_HOUR
# find $DIR_HOUR -mtime +1 -delete

if [[ $BAK_FILE == $MATCH_MONTH ]]; then
    uploadFile
fi

rm -f $FULL_BAK_FILE_TAR

